﻿using System;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Yoozoo.Gameplay.Liberty.PlayerController
{
    [RequireComponent(typeof(RectTransform))]
    public class MoveUIPanel : MonoBehaviour,IDragHandler, IPointerDownHandler, IPointerUpHandler
    {
        public RectTransform analogObject;
        public RectTransform anchorPoint;
        
        private VirtualAnalog _virtualAnalog;

        private Vector2 originAnchordPos => anchorPoint.anchoredPosition;
        
        private void Awake()
        {
            _virtualAnalog = analogObject.GetComponent<VirtualAnalog>();
            _virtualAnalog.transform.localPosition = anchorPoint.localPosition;
            //originAnchordPos = analogObject.anchoredPosition;
        }
        
        public void OnDrag(PointerEventData ped)
        {
            _virtualAnalog.OnDrag(ped);
        }

        public void OnPointerDown(PointerEventData ped)
        {
            Vector2 pos;
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)analogObject.parent, ped.position,
                    ped.pressEventCamera, out pos))
            {
                
                pos.x += (analogObject.pivot.x - 0.5f) * analogObject.rect.width / 2;
                pos.y += (analogObject.pivot.y - 0.5f) * analogObject.rect.height / 2;
                
                var parentRect = ((RectTransform)analogObject.parent);
                pos.x += (parentRect.pivot.x - 0.5f) * parentRect.rect.width;
                pos.y += (parentRect.pivot.y - 0.5f) * parentRect.rect.height;
                analogObject.localPosition = pos;
                
                _virtualAnalog.OnDrag(ped);
            }
        }

        public void OnPointerUp(PointerEventData ped)
        {
            _virtualAnalog.OnPointerUp(ped);
            analogObject.localPosition = anchorPoint.localPosition;
        }


    }
}